package com.example.springboot.config.feign;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Objects;

/**
 *
 * feign获取服务端抛出的原生异常
 *
 * @Author:ChenZhangKun
 * @Date: 2022/11/26 14:41
 */
@Configuration
public class FeignInterceptor  {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(attributes)){
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()){
                    String element = headerNames.nextElement();
                    String headerValue = request.getHeader(element);
                    requestTemplate.header(element,headerValue);
                }
                // 增加请求头
                if (request.getHeader("feign")==null){
                    requestTemplate.header("feign","feign");
                }
            }
        };
    }
    @Bean
    public OpenFeignErrorDecoder openFeignErrorDecoder(){
        return new OpenFeignErrorDecoder();
    }
}
